//
//  EditVC.m
//  WuyouTang
//
//  Created by YunBao on 2018/6/14.
//  Copyright © 2018年 cat. All rights reserved.
//

#import "EditVC.h"

#import "EditCell.h"
#import "EditHeader.h"
#import "AFNetworking.h"
#import "Utils.h"
#import <SDWebImage/SDImageCache.h>
#import <MobileCoreServices/MobileCoreServices.h>
@import CoreLocation;
@interface EditVC ()<TZImagePickerControllerDelegate,UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIPickerViewDelegate, UIPickerViewDataSource,CLLocationManagerDelegate> {
    
    UIImage *iconImage;
    
    MyTextField *name_tf;
    MyTextField *birth_tf;
    MyTextField *sex_tf;
    MyTextField *location_tf;
    MyTextField *signature_tf;
    UILabel *signature_num;
    
    UIView *cityPickBack;
    UIPickerView *cityPicker;
    //省市区-数组
    NSArray *province;
    NSArray *city;
    NSArray *district;
    
    //省市区-字符串
    NSString *provinceStr;
    NSString *cityStr;
    NSString *districtStr;
    
    NSDictionary *areaDic;
    NSString *selectedProvince;
    
    UIView *birthPickBack;
    UIDatePicker *birthPicker;
    NSString *birthStr;
    
    CLLocationManager   *_lbsManager;
    NSString *normalProvince;
    NSString *normalCity;
    NSString *normalDistrict;


}
@property(nonatomic,assign)BOOL iconChange;
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)EditHeader *tabHeader;

@end

@implementation EditVC
- (UIStatusBarStyle)preferredStatusBarStyle {
    if (@available(iOS 13.0,*)) {
        return UIStatusBarStyleDarkContent;
    }
    return UIStatusBarStyleDefault;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;
    normalProvince = @"";
    normalCity = @"";
    normalDistrict = @"";
    self.iconChange = NO;
    self.titleL.text = YZMsg(@"编辑资料");
    self.rightBtn.hidden = NO;
    [self.rightBtn setTitle:YZMsg(@"保存") forState:0];
    
    self.subNavi.backgroundColor =  UIColor.whiteColor;
    self.titleL.textColor = UIColor.blackColor;
    [self.leftBtn setImage:[UIImage imageNamed:@"pub_back_black"] forState:0];
    self.naviLine.hidden = NO;
    self.naviLine.backgroundColor = RGB(245, 245, 245);

    [self.view addSubview:self.tableView];
    [self.tableView setTableHeaderView:self.tabHeader];
    
    
    NSBundle *bundle = [NSBundle mainBundle];
    NSString *plistPath = [bundle pathForResource:@"area" ofType:@"plist"];
    areaDic = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
    
    NSArray *components = [areaDic allKeys];
    NSArray *sortedArray = [components sortedArrayUsingComparator: ^(id obj1, id obj2) {
        
        if ([obj1 integerValue] > [obj2 integerValue]) {
            return (NSComparisonResult)NSOrderedDescending;
        }
        
        if ([obj1 integerValue] < [obj2 integerValue]) {
            return (NSComparisonResult)NSOrderedAscending;
        }
        return (NSComparisonResult)NSOrderedSame;
    }];
    
    NSMutableArray *provinceTmp = [[NSMutableArray alloc] init];
    for (int i=0; i<[sortedArray count]; i++) {
        NSString *index = [sortedArray objectAtIndex:i];
        NSArray *tmp = [[areaDic objectForKey: index] allKeys];
        [provinceTmp addObject: [tmp objectAtIndex:0]];
    }
    //---> //rk_3-7 修复首次加载问题
    province = [[NSArray alloc] initWithArray: provinceTmp];
    NSString *index = [sortedArray objectAtIndex:0];
    //NSString *selected = [province objectAtIndex:0];
    selectedProvince = [province objectAtIndex:0];
    NSDictionary *proviceDic = [NSDictionary dictionaryWithDictionary: [[areaDic objectForKey:index]objectForKey:selectedProvince]];
    
    NSArray *cityArray = [proviceDic allKeys];
    NSDictionary *cityDic = [NSDictionary dictionaryWithDictionary: [proviceDic objectForKey: [cityArray objectAtIndex:0]]];
    //city = [[NSArray alloc] initWithArray: [cityDic allKeys]];
    
    NSArray *citySortedArray = [cityArray sortedArrayUsingComparator: ^(id obj1, id obj2) {
        if ([obj1 integerValue] > [obj2 integerValue]) {
            return (NSComparisonResult)NSOrderedDescending;//递减
        }
        if ([obj1 integerValue] < [obj2 integerValue]) {
            return (NSComparisonResult)NSOrderedAscending;//上升
        }
        return (NSComparisonResult)NSOrderedSame;
    }];
    NSMutableArray *m_array = [[NSMutableArray alloc] init];
    for (int i=0; i<[citySortedArray count]; i++) {
        NSString *index = [citySortedArray objectAtIndex:i];
        NSArray *temp = [[proviceDic objectForKey: index] allKeys];
        [m_array addObject: [temp objectAtIndex:0]];
    }
    city = [NSArray arrayWithArray:m_array];
    //<-----------
    
    NSString *selectedCity = [city objectAtIndex: 0];
    district = [[NSArray alloc] initWithArray: [cityDic objectForKey: selectedCity]];
    birthStr = [Config getUserBirth];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFiledEditChanged:) name:UITextFieldTextDidChangeNotification object:nil];
    
     [self location];
    
}
#pragma mark - textfield 监听字数变化
-(void)textFiledEditChanged:(NSNotification *)noti {
    MyTextField *textField = (MyTextField *)noti.object;
    NSString *toBeString = textField.text;
    NSString *lang = [[[UITextInputMode activeInputModes]firstObject] primaryLanguage]; // 键盘输入模式
    if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [textField markedTextRange];//获取高亮部分
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        //没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position) {
            //签名tf
            if (textField == signature_tf) {
                if (toBeString.length > 20) {
                    textField.text = [toBeString substringToIndex:20];
                    //signature_num.text = [NSString stringWithFormat:@"%lu/20",(20-textField.text.length)];
                    signature_num.text = [NSString stringWithFormat:@"%lu/20",textField.text.length];
                }else{
                    //signature_num.text = [NSString stringWithFormat:@"%lu/20",(20-toBeString.length)];
                    signature_num.text = [NSString stringWithFormat:@"%lu/20",toBeString.length];
                }
            }
            //昵称tf
            if (textField == name_tf) {
                if (toBeString.length > 8) {
                    textField.text = [toBeString substringToIndex:8];
                    [MBProgressHUD showPop:YZMsg(@"昵称最多可编辑8个字")];
                }
            }
        }else{
            //有高亮选择的字符串，则暂不对文字进行统计和限制
        }
    }else{
        // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
        if (textField == signature_tf) {
            if (toBeString.length > 20) {
                textField.text = [toBeString substringToIndex:20];
                signature_num.text = [NSString stringWithFormat:@"%lu/20",textField.text.length];
            }else{
                signature_num.text = [NSString stringWithFormat:@"%lu/20",toBeString.length];
            }
        }
        if (textField == name_tf) {
            if (toBeString.length > 8) {
                textField.text = [toBeString substringToIndex:8];
                [MBProgressHUD showPop:YZMsg(@"昵称最多可编辑8个字")];
            }
        }
    }
    
}
#pragma mark - 保存信息
-(void)clickSaveInfo {
    [self.view endEditing:YES];
    BOOL i_change = NO;
    //头像更改过
    if (_iconChange == YES) {
        i_change = YES;
        YBWeakSelf;
        //AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
        NSString *url = [purl stringByAppendingFormat:@"?service=User.updateAvatar&uid=%@&token=%@",[Config getOwnID],[Config getOwnToken]];
        [[WYNetworking ybnetManager] POST:url parameters:nil headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            if (iconImage) {
                [formData appendPartWithFileData:[Utils compressImage:iconImage] name:@"file" fileName:[self getVideoNameBaseCurrentTime:@".png"] mimeType:@"image/jpeg"];
            }
        }progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
            NSLog(@"-------%@",responseObject);
            NSArray *data = [responseObject valueForKey:@"data"];
            NSString *ret = [NSString stringWithFormat:@"%@",[responseObject valueForKey:@"ret"]];
            if ([ret isEqual:@"200"]) {
                NSNumber *number = [data valueForKey:@"code"] ;
                if([number isEqualToNumber:[NSNumber numberWithInt:0]]){
                    
                    weakSelf.iconChange = NO;
                    //[[SDImageCache sharedImageCache] clearDisk];
                    [[SDImageCache sharedImageCache]clearDiskOnCompletion:^{
                        
                    }];
                    [[SDImageCache sharedImageCache] clearMemory];//可有可无
                    NSString *info = [[data valueForKey:@"info"] firstObject];
                    NSString *avatar = [info valueForKey:@"avatar"];
                    NSString *avatar_thumb = [info valueForKey:@"avatar_thumb"];
                    
                    [Config saveUserAvatar:avatar];
                    [Config saveUserAvatarThumb:avatar_thumb];
                    //[MBProgressHUD showPop:YZMsg(@"更改成功")];
                }else if ([number isEqual:@"700"]) {
                    [PublicObj tokenExpired:[data valueForKey:@"msg"]];
                }
            }else{
                [weakSelf.tabHeader.iconIV sd_setImageWithURL:[NSURL URLWithString:[Config getUserAvatar]]];
                [MBProgressHUD showPop:[responseObject valueForKey:@"msg"]];
            }
        }failure:^(NSURLSessionDataTask *task, NSError *error) {
            [weakSelf.tabHeader.iconIV sd_setImageWithURL:[NSURL URLWithString:[Config getUserAvatar]]];
            [MBProgressHUD showPop:YZMsg(@"上传失败")];
        }];
    }
    
    NSLog(@"name-%@===birth-%@===sex-%@===location-%@===signature-%@",name_tf.text,birth_tf.text,sex_tf.text,location_tf.text,signature_tf.text);
    //判断更改了那些信息
    NSMutableDictionary *m_dic = [NSMutableDictionary dictionary];
    //名字
    if (![name_tf.text isEqual:[Config getOwnNicename]]) {
        [m_dic setObject:name_tf.text forKey:@"user_nickname"];
    }
    //生日
    if (![birth_tf.text isEqual:[Config getUserBirth]]) {
        [m_dic setObject:birth_tf.text forKey:@"birthday"];
    }
    //性别
    NSString *sexStr;
    if ([sex_tf.text isEqual:YZMsg(@"男")]) {
        sexStr = @"1";
    }else{
        sexStr = @"2";
    }
    if (![sexStr isEqual:[Config getUserSex]]) {
        [m_dic setObject:sexStr forKey:@"sex"];
    }
    //地区
    if (![location_tf.text isEqual:[Config getUserHomeTown]]) {
        [m_dic setObject:provinceStr forKey:@"province"];
        [m_dic setObject:cityStr forKey:@"city"];
        [m_dic setObject:districtStr forKey:@"area"];
    }
    //签名
    if (![signature_tf.text isEqual:[Config getOwnSignature]]) {
        [m_dic setObject:signature_tf.text forKey:@"signature"];
    }
    if (![m_dic count]) {
        //没有更改任何信息
        i_change==YES ? [MBProgressHUD showPop:YZMsg(@"设置头像成功")]: [MBProgressHUD showPop:YZMsg(@"未修改资料")];
        if (i_change) {
//            [self.navigationController popViewControllerAnimated:YES];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });

        }
        return;
    }
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:m_dic options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonStr = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSString *saveUrl = [NSString stringWithFormat:@"User.updateFields&uid=%@&token=%@&fields=%@",[Config getOwnID],[Config getOwnToken],jsonStr];
    saveUrl = [saveUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    [WYNetworking postWithUrl:saveUrl Dic:nil Suc:^(int code, id info, NSString *msg) {
        if (code == 0) {
            if ([m_dic valueForKey:@"user_nickname"]) {
                //说明更改了-名字
                [Config saveOwnNicename:[NSString stringWithFormat:@"%@",[m_dic valueForKey:@"user_nickname"]]];
            }
            if ([m_dic valueForKey:@"birthday"]) {
                //说明更改了-生日
                [Config saveUserBirth:[NSString stringWithFormat:@"%@",[m_dic valueForKey:@"birthday"]]];
            }
            if ([m_dic valueForKey:@"sex"]) {
                //说明更改了-性别
                [Config saveUserSex:[NSString stringWithFormat:@"%@",[m_dic valueForKey:@"sex"]]];
            }
            if ([m_dic valueForKey:@"province"]) {
                //说明更改了-地址
                [Config saveUserHomeTown:[NSString stringWithFormat:@"%@%@%@",[m_dic valueForKey:@"province"],[m_dic valueForKey:@"city"],[m_dic valueForKey:@"area"]]];
            }
            if ([m_dic valueForKey:@"signature"]) {
                //说明更改了-签名
                [Config saveOwnSignature:[NSString stringWithFormat:@"%@",[m_dic valueForKey:@"signature"]]];
            }
            NSDictionary *ifnoDic = [info firstObject];
            [MBProgressHUD showPop:minstr([ifnoDic valueForKey:@"msg"])];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }else{
            [MBProgressHUD showPop:msg];
        }
    } Fail:^(id fail) {
        
    }];
   
}

-(void)clickChangeBirth {
    if (!birthPickBack) {
        birthPickBack = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _window_width, _window_height)];
        birthPickBack.backgroundColor = RGB_COLOR(@"#000000", 0.3);
        [self.view addSubview:birthPickBack];
        
        UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(0, _window_height-240, _window_width, 40)];
        titleView.backgroundColor = RGB_COLOR(@"#ececec", 1);
        [birthPickBack addSubview:titleView];
        
        UIButton *cancleBtn = [UIButton buttonWithType:0];
        cancleBtn.frame = CGRectMake(20, 0, 80, 40);
        cancleBtn.tag = 100;
        [cancleBtn setTitle:YZMsg(@"取消") forState:0];
        [cancleBtn setTitleColor:[UIColor blueColor] forState:0];
        [cancleBtn addTarget:self action:@selector(birthCancleOrSure:) forControlEvents:UIControlEventTouchUpInside];
        [titleView addSubview:cancleBtn];
        UIButton *sureBtn = [UIButton buttonWithType:0];
        sureBtn.frame = CGRectMake(_window_width-100, 0, 80, 40);
        sureBtn.tag = 101;
        [sureBtn setTitle:YZMsg(@"确定") forState:0];
        [sureBtn setTitleColor:[UIColor blueColor] forState:0];
        [sureBtn addTarget:self action:@selector(birthCancleOrSure:) forControlEvents:UIControlEventTouchUpInside];
        [titleView addSubview:sureBtn];
        
        birthPicker = [[UIDatePicker alloc]initWithFrame:CGRectMake(0, _window_height-200, _window_width, 200)];
        if (@available(iOS 13.4,*)) {
            birthPicker.preferredDatePickerStyle = UIDatePickerStyleWheels;
            //设置样式后必须重新设置尺寸
            birthPicker.frame = CGRectMake(0, _window_height-200, _window_width, 200);
        }
        NSDate *currentDate = [NSDate date];
        [birthPicker setMaximumDate:currentDate];
        NSDateFormatter  *formatter = [[NSDateFormatter  alloc]init];
        [formatter  setDateFormat : @"yyyy-MM-dd" ];
        NSString  *mindateStr =  @"1950-01-01" ;
        NSDate  *mindate = [formatter  dateFromString :mindateStr];
        birthPicker.minimumDate = mindate;
        birthPicker.maximumDate=[NSDate date];
        [birthPicker addTarget:self action:@selector(oneDatePickerValueChanged:) forControlEvents:UIControlEventValueChanged ];
        birthPicker.datePickerMode = UIDatePickerModeDate;
        birthPicker.backgroundColor = [UIColor whiteColor];
        //设置为中文
        NSLocale *locale = [[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"];
        if (![lagType isEqual:ZH_CN]) {
            locale = [[NSLocale alloc]initWithLocaleIdentifier:@"en"];
        }
        birthPicker.locale =locale;
        [birthPickBack addSubview:birthPicker];
        
    }else{
        birthPickBack.hidden = NO;
    }
    
}
- (void)birthCancleOrSure:(UIButton *)button{
    if (button.tag == 100) {
        //return;
    }else{
        //未滑动peaker直接点击确定
        if (birthStr.length<=0||[birthStr isEqual:[Config getUserBirth]]) {
            NSDate *currentDate = [NSDate date];//获取当前时间，日期
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"YYYY-MM-dd"];
            birthStr = [dateFormatter stringFromDate:currentDate];
        }
        birth_tf.text = birthStr;
    }
    birthPickBack.hidden = YES;
   
}


- (void)oneDatePickerValueChanged:(UIDatePicker *) sender {
    NSDate *select = [sender date]; // 获取被选中的时间
    NSDateFormatter *selectDateFormatter = [[NSDateFormatter alloc] init];
    [selectDateFormatter setDateFormat:@"YYYY-MM-dd"];
    birthStr = [selectDateFormatter stringFromDate:select]; // 把date类型转为设置好格式的string类型
}

-(void)clickChangeSex {
    
    RKActionSheet *sheet = [[RKActionSheet alloc]initWithTitle:nil];
    [sheet addActionWithType:RKSheet_Default andTitle:YZMsg(@"男") complete:^{
        sex_tf.text = YZMsg(@"男");
    }];
    [sheet addActionWithType:RKSheet_Default andTitle:YZMsg(@"女") complete:^{
        sex_tf.text = YZMsg(@"女");
    }];
    [sheet addActionWithType:RKSheet_Cancle andTitle:YZMsg(@"取消") complete:^{
    }];
    [sheet showSheet];
    
}

//城市选择
-(void)clickChangeLocation {
    
    if (!cityPickBack) {
        cityPickBack = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _window_width, _window_height)];
        cityPickBack.backgroundColor = RGB_COLOR(@"#000000", 0.3);
        [self.view addSubview:cityPickBack];
        
        UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(0, _window_height-240, _window_width, 40)];
        titleView.backgroundColor = RGB_COLOR(@"#ececec", 1);
        [cityPickBack addSubview:titleView];
        
        UIButton *cancleBtn = [UIButton buttonWithType:0];
        cancleBtn.frame = CGRectMake(20, 0, 80, 40);
        cancleBtn.tag = 100;
        [cancleBtn setTitle:YZMsg(@"取消") forState:0];
        [cancleBtn setTitleColor:[UIColor blueColor] forState:0];
        [cancleBtn addTarget:self action:@selector(cityCancleOrSure:) forControlEvents:UIControlEventTouchUpInside];
        [titleView addSubview:cancleBtn];
        UIButton *sureBtn = [UIButton buttonWithType:0];
        sureBtn.frame = CGRectMake(_window_width-100, 0, 80, 40);
        sureBtn.tag = 101;
        [sureBtn setTitle:YZMsg(@"确定") forState:0];
        [sureBtn setTitleColor:[UIColor blueColor] forState:0];
        [sureBtn addTarget:self action:@selector(cityCancleOrSure:) forControlEvents:UIControlEventTouchUpInside];
        [titleView addSubview:sureBtn];
        
        cityPicker = [[UIPickerView alloc]initWithFrame:CGRectMake(0, _window_height-200, _window_width, 200)];
        cityPicker.backgroundColor = [UIColor whiteColor];
        cityPicker.delegate = self;
        cityPicker.dataSource = self;
        cityPicker.showsSelectionIndicator = YES;
        [cityPicker selectRow: 0 inComponent: 0 animated: YES];
        [cityPickBack addSubview:cityPicker];
        
        [self setLocationAddress];
    }else{
        cityPickBack.hidden = NO;
    }
    
}
- (void)cityCancleOrSure:(UIButton *)button{
    if (button.tag == 100) {
        //return;
    }else{
        NSInteger provinceIndex = [cityPicker selectedRowInComponent: 0];
        NSInteger cityIndex = [cityPicker selectedRowInComponent: 1];
        NSInteger districtIndex = [cityPicker selectedRowInComponent: 2];
        
        provinceStr = [province objectAtIndex: provinceIndex];
        cityStr = [city objectAtIndex: cityIndex];
        districtStr = [district objectAtIndex:districtIndex];
        NSString *dizhi = [NSString stringWithFormat:@"%@%@%@",provinceStr,cityStr,districtStr];
        location_tf.text = dizhi;
    }
    cityPickBack.hidden = YES;
   
}

#pragma mark- Picker Data Source Methods
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    if (pickerView == cityPicker) {
        return 3;
    }
    return 0;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (pickerView == cityPicker) {
        if (component == 0) {
            return [province count];
        }
        else if (component == 1) {
            return [city count];
        }
        else {
            return [district count];
        }
    }else{
        return 100;
    }
}


#pragma mark- Picker Delegate Methods

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if (pickerView == cityPicker) {
        if (component == 0) {
            return [province objectAtIndex: row];
        }
        else if (component == 1) {
            return [city objectAtIndex: row];
        }
        else {
            return [district objectAtIndex: row];
        }
    }else{
        return nil;
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    if (pickerView == cityPicker) {
        if (component == 0) {
            selectedProvince = [province objectAtIndex: row];
            NSDictionary *tmp = [NSDictionary dictionaryWithDictionary: [areaDic objectForKey: [NSString stringWithFormat:@"%ld", row]]];
            NSDictionary *dic = [NSDictionary dictionaryWithDictionary: [tmp objectForKey: selectedProvince]];
            NSArray *cityArray = [dic allKeys];
            NSArray *sortedArray = [cityArray sortedArrayUsingComparator: ^(id obj1, id obj2) {
                
                if ([obj1 integerValue] > [obj2 integerValue]) {
                    return (NSComparisonResult)NSOrderedDescending;//递减
                }
                if ([obj1 integerValue] < [obj2 integerValue]) {
                    return (NSComparisonResult)NSOrderedAscending;//上升
                }
                return (NSComparisonResult)NSOrderedSame;
            }];
            
            NSMutableArray *array = [[NSMutableArray alloc] init];
            for (int i=0; i<[sortedArray count]; i++) {
                NSString *index = [sortedArray objectAtIndex:i];
                NSArray *temp = [[dic objectForKey: index] allKeys];
                [array addObject: [temp objectAtIndex:0]];
            }
            
            city = [[NSArray alloc] initWithArray: array];
            
            NSDictionary *cityDic = [dic objectForKey: [sortedArray objectAtIndex: 0]];
            district = [[NSArray alloc] initWithArray: [cityDic objectForKey: [city objectAtIndex: 0]]];
            [cityPicker selectRow: 0 inComponent: 1 animated: YES];
            [cityPicker selectRow: 0 inComponent: 2 animated: YES];
            [cityPicker reloadComponent: 1];
            [cityPicker reloadComponent: 2];
            
        } else if (component == 1) {
            NSString *provinceIndex = [NSString stringWithFormat: @"%ld", [province indexOfObject: selectedProvince]];
            NSDictionary *tmp = [NSDictionary dictionaryWithDictionary: [areaDic objectForKey: provinceIndex]];
            NSDictionary *dic = [NSDictionary dictionaryWithDictionary: [tmp objectForKey: selectedProvince]];
            NSArray *dicKeyArray = [dic allKeys];
            NSArray *sortedArray = [dicKeyArray sortedArrayUsingComparator: ^(id obj1, id obj2) {
                
                if ([obj1 integerValue] > [obj2 integerValue]) {
                    return (NSComparisonResult)NSOrderedDescending;
                }
                
                if ([obj1 integerValue] < [obj2 integerValue]) {
                    return (NSComparisonResult)NSOrderedAscending;
                }
                return (NSComparisonResult)NSOrderedSame;
            }];
            
            NSDictionary *cityDic = [NSDictionary dictionaryWithDictionary: [dic objectForKey: [sortedArray objectAtIndex: row]]];
            NSArray *cityKeyArray = [cityDic allKeys];
            
            district = [[NSArray alloc] initWithArray: [cityDic objectForKey: [cityKeyArray objectAtIndex:0]]];
            [cityPicker selectRow: 0 inComponent: 2 animated: YES];
            [cityPicker reloadComponent: 2];
        }
    }else{
        
    }
    
}


- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    if (component == 0) {
        return 80;
    }
    else if (component == 1) {
        return 100;
    }
    else {
        return 115;
    }
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    UILabel *myView = nil;
    if (pickerView == cityPicker) {
        if (component == 0) {
            myView = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, _window_width/3, 30)];
            myView.textAlignment = NSTextAlignmentCenter;
            myView.text = [province objectAtIndex:row];
            myView.font = [UIFont systemFontOfSize:14];
            myView.backgroundColor = [UIColor clearColor];
        }
        else if (component == 1) {
            myView = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, _window_width/3, 30)];
            myView.textAlignment = NSTextAlignmentCenter;
            myView.text = [city objectAtIndex:row];
            myView.font = [UIFont systemFontOfSize:14];
            myView.backgroundColor = [UIColor clearColor];
        }
        else {
            myView = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, _window_width/3, 30)];
            myView.textAlignment = NSTextAlignmentCenter;
            myView.text = [district objectAtIndex:row];
            myView.font = [UIFont systemFontOfSize:14];
            myView.backgroundColor = [UIColor clearColor];
        }
    }
    return myView;
}


#pragma mark -
#pragma mark - UITableViewDelegate,UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 4) {
        //签名
        return 80;
    }else{
        return 60;
    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 5;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    EditCell *cell = [EditCell cellWithTab:tableView andIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = UIColor.whiteColor;
    switch (indexPath.row) {
        case 0:{
            cell.nameTF.text = [Config getOwnNicename];
            name_tf = cell.nameTF;
        }break;
        case 1:{
            cell.birthTF.text = [Config getUserBirth];
            cell.birthTF.userInteractionEnabled = NO;
            birth_tf = cell.birthTF;
            
        }break;
        case 2:{
            if ([[Config getUserSex]isEqual:@"1"]) {
                cell.sexTF.text = YZMsg(@"男");
            }else{
                cell.sexTF.text = YZMsg(@"女");
            }
            cell.sexTF.userInteractionEnabled = NO;
            sex_tf = cell.sexTF;
            
        }break;
        case 3:{
            NSString *homeStr = [PublicObj checkNull:[Config getUserHomeTown]]?@"":[Config getUserHomeTown];
            if ([homeStr isEqual:@"城市未填写"]) {//不要翻译
                homeStr = @"";
            }
            cell.locationTF.text = homeStr;
            cell.locationTF.userInteractionEnabled = NO;
            location_tf = cell.locationTF;
        }break;
        case 4:{
            cell.signatoryTF.text = [Config getOwnSignature];
            //2020-6-20改为显示输入的字数
            //cell.numL.text = [NSString stringWithFormat:@"%lu/20",(20-cell.signatoryTF.text.length)];
            cell.numL.text = [NSString stringWithFormat:@"%lu/20",cell.signatoryTF.text.length];
            signature_num = cell.numL;
            signature_tf = cell.signatoryTF;
        }break;
        default:
            break;
    }
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (indexPath.row) {
        case 0:{
            
        }break;
        case 1:{
            [self clickChangeBirth];
            NSLog(@"bitth");
        }break;
        case 2:{
            NSLog(@"sex");
            [self clickChangeSex];
        } break;
        case 3:{
            NSLog(@"location");
            [self clickChangeLocation];
        }break;
        case 4:{

        }break;
            
        default:
            break;
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

#pragma mark -   UIImagePickerControllerDelegate
//拍照
-(void)clickTake {
    UIImagePickerController *imagePickerController = [UIImagePickerController new];
    imagePickerController.allowsEditing = YES;
    imagePickerController.delegate = self;
    imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
    imagePickerController.allowsEditing = YES;
    imagePickerController.showsCameraControls = YES;
    imagePickerController.cameraDevice = UIImagePickerControllerCameraDeviceRear;
    //imagePickerController.mediaTypes = @[(NSString *)kUTTypeImage];
    imagePickerController.modalPresentationStyle = 0;
    [self presentViewController:imagePickerController animated:YES completion:nil];
}
//选照
-(void)clickSel {
    /*
    UIImagePickerController *imagePickerController = [UIImagePickerController new];
    imagePickerController.allowsEditing = YES;
    imagePickerController.delegate = self;
    imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePickerController.allowsEditing = YES;
    imagePickerController.mediaTypes = @[(NSString *)kUTTypeImage];
    [UIApplication sharedApplication].statusBarHidden = YES;
    if (@available(iOS 11, *)) {
        UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAutomatic;
    }
    imagePickerController.modalPresentationStyle = 0;
    [self presentViewController:imagePickerController animated:YES completion:nil];
    */
    TZImagePickerController *imagePC = [[TZImagePickerController alloc]initWithMaxImagesCount:1 delegate:self];
    imagePC.preferredLanguage = [lagType isEqual:ZH_CN] ? @"zh-Hans":@"en";
    imagePC.showSelectBtn = NO;
    imagePC.allowPickingOriginalPhoto = NO;
    imagePC.oKButtonTitleColorNormal = Pink_Cor;
    imagePC.allowTakePicture = NO;
    imagePC.allowTakeVideo = NO;
    imagePC.allowPickingVideo = NO;
    imagePC.allowPickingMultipleVideo = NO;
    imagePC.modalPresentationStyle = 0;
    imagePC.allowCrop = YES;
    imagePC.cropRect = CGRectMake(0, (_window_height-_window_width)/2, _window_width, _window_width);
    [[[YBBaseAppDelegate sharedAppDelegate] topViewController]presentViewController:imagePC animated:YES completion:nil];
}
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto{
    _iconChange = YES;
    iconImage = photos[0];
    _tabHeader.iconIV.image = iconImage;
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    if (@available(iOS 11, *)) {
        UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    _iconChange = YES;
    
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        //先把图片转成NSData
        UIImage* image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
        iconImage = image;
        _tabHeader.iconIV.image = image;
        
        /*
         NSData *data;
         if (UIImagePNGRepresentation(image) == nil) {
         data = UIImageJPEGRepresentation(image, 1.0);
         }else{
         data = UIImagePNGRepresentation(image);
         }
         //图片保存的路径
         NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
         NSFileManager *fileManager = [NSFileManager defaultManager];
         //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png
         [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
         [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.png"] contents:data attributes:nil];
         
         //得到选择后沙盒中图片的完整路径
         
         NSString  *filePath = [[NSString alloc]initWithFormat:@"%@%@",DocumentsPath, @"/image.png"];
         NSURL *imageURL = [NSURL URLWithString:filePath];
         UIImage *image = [UIImage imageWithContentsOfFile:filePath];
         */
        
        [picker dismissViewControllerAnimated:YES completion:^{
            [UIApplication sharedApplication].statusBarHidden=NO;
        }];
        
    }
}
- (NSString *)getVideoNameBaseCurrentTime:(NSString *)suf {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
    NSString *nameStr = [[dateFormatter stringFromDate:[NSDate date]] stringByAppendingString:suf];
    return [NSString stringWithFormat:@"%@_IOS_avatar%@",[Config getOwnID],nameStr];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:^{
        [UIApplication sharedApplication].statusBarHidden=NO;
    }];
}
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    if ([UIDevice currentDevice].systemVersion.floatValue < 11) {
        return;
    }
    if ([viewController isKindOfClass:NSClassFromString(@"PUPhotoPickerHostViewController")]) {
        [viewController.view.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj.frame.size.width < 42) {
                [viewController.view sendSubviewToBack:obj];
                *stop = YES;
            }
        }];
    }
}
#pragma mark - seg/get

-(EditHeader *)tabHeader {
    if (!_tabHeader) {
        __weak EditVC *weakSelf = self;
        _tabHeader = [[[NSBundle mainBundle]loadNibNamed:@"EditHeader" owner:nil options:nil] objectAtIndex:0];
        _tabHeader.backgroundColor = UIColor.whiteColor;
        [_tabHeader.iconIV sd_setImageWithURL:[NSURL URLWithString:[Config getUserAvatar]]];
        _tabHeader.event = ^(id event) {
            [weakSelf showSheetView];
        };
    }
    return _tabHeader;
}

-(void)showSheetView {
    YBWeakSelf;
    RKActionSheet *sheet = [[RKActionSheet alloc]initWithTitle:@""];
    [sheet addActionWithType:RKSheet_Default andTitle:YZMsg(@"相机") complete:^{
        [weakSelf clickTake];
    }];
    [sheet addActionWithType:RKSheet_Default andTitle:YZMsg(@"相册") complete:^{
        [weakSelf clickSel];
    }];
    [sheet addActionWithType:RKSheet_Cancle andTitle:YZMsg(@"取消") complete:^{
    }];
    [sheet showSheet];
}

-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,64+statusbarHeight, _window_width, _window_height-64-statusbarHeight-ShowDiff) style:UITableViewStyleGrouped];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = UIColor.whiteColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
    }
    return _tableView;
}


- (void)clickNaviRightBtn {
    [self clickSaveInfo];
}

#pragma mark -
-(void)location{
    [[RKLBSManager shareManager]startLocation];
    [RKLBSManager shareManager].fromEdit = YES;
    [[RKLBSManager shareManager]locationComplete:^(BOOL isSuc, NSArray<CLPlacemark *> *placemarks, NSArray<NSString *> *pcaArray) {
        normalProvince = pcaArray[0];
        normalCity = pcaArray[1];
        normalDistrict = pcaArray[2];
    }];
}
/*
-(void)location{
    if (!_lbsManager) {
        _lbsManager = [[CLLocationManager alloc] init];
        [_lbsManager setDesiredAccuracy:kCLLocationAccuracyBest];
        _lbsManager.delegate = self;
        // 兼容iOS8定位
        SEL requestSelector = NSSelectorFromString(@"requestWhenInUseAuthorization");
        if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined && [_lbsManager respondsToSelector:requestSelector]) {
            [_lbsManager requestWhenInUseAuthorization];  //调用了这句,就会弹出允许框了.
        } else {
            [_lbsManager startUpdatingLocation];
        }
    }
}
- (void)stopLbs {
    [_lbsManager stopUpdatingHeading];
    _lbsManager.delegate = nil;
    _lbsManager = nil;
}
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    if (status == kCLAuthorizationStatusRestricted || status == kCLAuthorizationStatusDenied) {
        [self stopLbs];
    } else {
        [_lbsManager startUpdatingLocation];
    }
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    [self stopLbs];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    
    CLLocation *newLocatioin = locations[0];
    
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:newLocatioin completionHandler:^(NSArray *placemarks, NSError *error) {
        if (!error) {
            CLPlacemark *placeMark = placemarks[0];
            NSString *addr = [NSString stringWithFormat:@"%@%@%@",placeMark.administrativeArea,placeMark.locality,placeMark.subLocality];
            NSLog(@"hhhhhhhh----:%@", addr);
            normalProvince =placeMark.administrativeArea;
            normalCity = placeMark.locality;
            normalDistrict = placeMark.subLocality;
        }
    }];
     [self stopLbs];
}
*/

-(void)setLocationAddress{
    int provinceIndex = 0;
    int cityIndex = 0;

    NSArray *components = [areaDic allKeys];
    NSArray *sortedArray = [components sortedArrayUsingComparator: ^(id obj1, id obj2) {
        
        if ([obj1 integerValue] > [obj2 integerValue]) {
            return (NSComparisonResult)NSOrderedDescending;
        }
        
        if ([obj1 integerValue] < [obj2 integerValue]) {
            return (NSComparisonResult)NSOrderedAscending;
        }
        return (NSComparisonResult)NSOrderedSame;
    }];
    
    NSMutableArray *provinceTmp = [[NSMutableArray alloc] init];
    for (int i=0; i<[sortedArray count]; i++) {
        NSString *index = [sortedArray objectAtIndex:i];
        NSArray *tmp = [[areaDic objectForKey: index] allKeys];
        [provinceTmp addObject: [tmp objectAtIndex:0]];
    }

    if (normalProvince.length > 0) {
        selectedProvince = normalProvince;

        for (int i = 0; i < province.count; i ++) {
            if ([normalProvince isEqual:province[i]]) {
                provinceIndex = i;
                NSString *index = [sortedArray objectAtIndex:i];

                NSDictionary *proviceDic = [NSDictionary dictionaryWithDictionary: [[areaDic objectForKey:index]objectForKey:normalProvince]];
                NSArray *cityArray = [proviceDic allKeys];
                NSDictionary *cityDic = [NSDictionary dictionaryWithDictionary: [proviceDic objectForKey: [cityArray objectAtIndex:i]]];

                NSArray *citySortedArray = [cityArray sortedArrayUsingComparator: ^(id obj1, id obj2) {
                    if ([obj1 integerValue] > [obj2 integerValue]) {
                        return (NSComparisonResult)NSOrderedDescending;//递减
                    }
                    if ([obj1 integerValue] < [obj2 integerValue]) {
                        return (NSComparisonResult)NSOrderedAscending;//上升
                    }
                    return (NSComparisonResult)NSOrderedSame;
                }];
                NSMutableArray *m_array = [[NSMutableArray alloc] init];
                for (int i=0; i<[citySortedArray count]; i++) {
                    NSString *index = [citySortedArray objectAtIndex:i];
                    NSArray *temp = [[proviceDic objectForKey: index] allKeys];
                    [m_array addObject: [temp objectAtIndex:0]];
                }
               NSArray *cityArr = [NSArray arrayWithArray:m_array];
                city =[NSArray arrayWithArray:m_array];
                for (int j = 0; j < cityArr.count; j ++) {
                    if ([normalCity isEqual:cityArr[j]]) {
                        cityIndex = j;
                        NSString *keys = [NSString stringWithFormat:@"%d",cityIndex];
                        NSDictionary *dicssss = [NSDictionary dictionaryWithDictionary: [proviceDic objectForKey: keys]];

                        NSString *selectedCity = [cityArr objectAtIndex: j];
                        district = [[NSArray alloc] initWithArray: [dicssss objectForKey: selectedCity]];

                        NSArray * districtArr = [[NSArray alloc] initWithArray: [dicssss objectForKey: selectedCity]];
                        for (int k = 0; k <districtArr.count; k ++) {
                            if ([normalDistrict isEqual:districtArr[k]]) {
                                [cityPicker selectRow: provinceIndex inComponent: 0 animated: YES];
                                [cityPicker reloadComponent: 1];

                                [cityPicker selectRow: cityIndex inComponent: 1 animated: YES];
                                [cityPicker reloadComponent: 2];

                                [cityPicker selectRow: k inComponent: 2 animated: YES];
                            }
                        }
                    }
                }
            }
        }
    }
    NSLog(@"province===:%@  \n city:%@   \ndistrict:%@",province,city,district);
}
@end
